package coreservlets.ch9;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class OrderPage extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String SHOPPINT_CART_SESSION_KEY = "shoppingCart";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		ShoppingCart cart;
		synchronized (session) {
			cart = (ShoppingCart) session
					.getAttribute(SHOPPINT_CART_SESSION_KEY);
			if (cart == null) {
				cart = new ShoppingCart();
				session.setAttribute(SHOPPINT_CART_SESSION_KEY, cart);
			}
			String itemID = req.getParameter("itemID");
			if (itemID != null) {
				String numItemString = req.getParameter("numItems");
				if (numItemString == null) {
					cart.addItem(itemID);
				} else {
					int numItems;
					try {
						numItems = Integer.parseInt(numItemString);
					} catch (NumberFormatException e) {
						numItems = 1;
					}
					cart.setNumOrdered(itemID, numItems);
				}
			}
		}
		// order status.
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		String title = "Status of Your Order";
		String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
				+ "Transitional//EN\">\n";
		out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title
				+ "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n"
				+ "<H1 ALIGN=\"CENTER\">" + title + "</H1>");
		synchronized (session) {
			List<ItemOrder> itemsOrdered = cart.getItemsOrdered();
			if (itemsOrdered.size() == 0) {
				out.println("<H2><I>No items in your cart...</I></H2>");
			} else {
				// If there is at least one item in cart, show table
				// of items ordered.
				out.println("<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
						+ "<TR BGCOLOR=\"#FFAD00\">\n"
						+ " <TH>Item ID<TH>Description\n"
						+ " <TH>Unit Cost<TH>Number<TH>Total Cost");
				ItemOrder order;
				// Rounds to two decimal places, inserts dollar
				// sign (or other currency symbol), etc., as
				// appropriate in current Locale.
				NumberFormat formatter = NumberFormat.getCurrencyInstance();
				// For each entry in shopping cart, make
				// table row showing ID, description, per-item
				// cost, number ordered, and total cost.
				// Put number ordered in textfield that user
				// can change, with "Update Order" button next
				// to it, which resubmits to this same page
				// but specifying a different number of items.
				for (int i = 0; i < itemsOrdered.size(); i++) {
					order = (ItemOrder) itemsOrdered.get(i);
					out.println("<TR>\n" + " <TD>"
							+ order.getItemID()
							+ "\n"
							+ " <TD>"
							+ order.getShortDescription()
							+ "\n"
							+ " <TD>"
							+ formatter.format(order.getUnitCost())
							+ "\n"
							+ " <TD>"
							+ "<FORM>\n"
							+ // Submit to current URL
							"<INPUT TYPE=\"HIDDEN\" NAME=\"itemID\"\n"
							+ " VALUE=\"" + order.getItemID() + "\">\n"
							+ "<INPUT TYPE=\"TEXT\" NAME=\"numItems\"\n"
							+ " SIZE=3 VALUE=\"" + order.getNumItems()
							+ "\">\n" + "<SMALL>\n"
							+ "<INPUT TYPE=\"SUBMIT\"\n "
							+ " VALUE=\"Update Order\">\n" + "</SMALL>\n"
							+ "</FORM>\n" + " <TD>"
							+ formatter.format(order.getTotalCost()));
				}
				String checkoutURL = resp.encodeURL("../Checkout.html");
				// "Proceed to Checkout" button below table
				out.println("</TABLE>\n" + "<FORM ACTION=\"" + checkoutURL
						+ "\">\n" + "<BIG><CENTER>\n"
						+ "<INPUT TYPE=\"SUBMIT\"\n"
						+ " VALUE=\"Proceed to Checkout\">\n"
						+ "</CENTER></BIG></FORM>");
			}
			out.println("</BODY></HTML>");
		}
	}
}
